// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有图表
    initCharts();

    // 初始化并开始更新时间
    updateTime();
    setInterval(updateTime, 1000);

    // 模拟数据更新
    setInterval(updateCharts, 5000);
});

// 更新当前时间显示
function updateTime() {
    const now = new Date();
    const timeElement = document.getElementById('current-time');

    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    timeElement.textContent = formattedTime;
}

// 初始化所有图表
function initCharts() {
    initMapChart();
    initStatusChart();
    initFrequencyChart();
    initEnvironmentChart();
}

// 初始化地图图表
function initMapChart() {
    const chartDom = document.getElementById('chart-map');
    const myChart = echarts.init(chartDom);

    const option = {
        backgroundColor: 'rgba(0, 0, 0, 0)',
        title: {
            text: '广西地区设备分布',
            left: 'center',
            textStyle: {
                color: '#fff',
                fontSize: 16
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: function(params) {
                return `${params.name}: ${params.value[2]} 台设备`;
            }
        },
        geo: {
            map: 'guangxi',
            roam: true,
            zoom: 1.2,
            label: {
                normal: {
                    show: true,
                    color: '#fff',
                    fontSize: 10
                }
            },
            itemStyle: {
                normal: {
                    areaColor: 'rgba(30, 144, 255, 0.1)',
                    borderColor: 'rgba(30, 144, 255, 0.5)'
                },
                emphasis: {
                    areaColor: 'rgba(30, 144, 255, 0.3)'
                }
            }
        },
        series: [
            {
                name: '设备分布',
                type: 'scatter',
                coordinateSystem: 'geo',
                data: [
                    {name: '河池', value: [108.085179, 24.700488, 85]},
                    {name: '柳州', value: [109.412578, 24.354875, 120]},
                    {name: '梧州', value: [111.323462, 23.478238, 75]},
                    {name: '南宁', value: [108.359656, 22.81328, 150]},
                    {name: '北海', value: [109.171374, 21.477419, 60]},
                    {name: '崇左', value: [107.347374, 22.377503, 40]}
                ],
                symbolSize: function(val) {
                    return val[2] / 5;
                },
                label: {
                    normal: {
                        show: false
                    },
                    emphasis: {
                        show: true,
                        formatter: function(params) {
                            return params.name + ': ' + params.value[2] + '台';
                        },
                        position: 'top',
                        textStyle: {
                            color: '#fff',
                            fontSize: 12
                        }
                    }
                },
                itemStyle: {
                    normal: {
                        color: '#1E90FF'
                    }
                }
            }
        ]
    };

    myChart.setOption(option);

    // 窗口大小变化时重绘图表
    window.addEventListener('resize', function() {
        myChart.resize();
    });

    return myChart;
}

// 初始化设备状态图表
function initStatusChart() {
    const chartDom = document.getElementById('chart-status');
    const myChart = echarts.init(chartDom);

    const option = {
        backgroundColor: 'rgba(0, 0, 0, 0)',
        title: {
            text: '设备状态分布',
            left: 'center',
            textStyle: {
                color: '#fff',
                fontSize: 14
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [
            {
                name: '设备状态',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                label: {
                    normal: {
                        show: true,
                        formatter: '{b}\n{d}%'
                    }
                },
                data: [
                    {value: 470, name: '正常', itemStyle: {color: '#00B42A'}},
                    {value: 20, name: '维护中', itemStyle: {color: '#FF7D00'}},
                    {value: 10, name: '故障', itemStyle: {color: '#F53F3F'}}
                ]
            }
        ]
    };

    myChart.setOption(option);

    // 窗口大小变化时重绘图表
    window.addEventListener('resize', function() {
        myChart.resize();
    });

    return myChart;
}

// 初始化设备使用频率图表
function initFrequencyChart() {
    const chartDom = document.getElementById('chart-frequency');
    const myChart = echarts.init(chartDom);

    const option = {
        backgroundColor: 'rgba(0, 0, 0, 0)',
        title: {
            text: '设备使用频率',
            left: 'center',
            textStyle: {
                color: '#fff',
                fontSize: 14
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '25%',
            containLabel: true
        },
        xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01],
            axisLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.3)'
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: 'rgba(255, 255, 255, 0.7)'
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.1)'
                }
            }
        },
        yAxis: {
            type: 'category',
            data: ['1号机', '2号机', '3号机', '4号机', '5号机'],
            axisLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.3)'
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: 'rgba(255, 255, 255, 0.7)'
            }
        },
        series: [
            {
                name: '使用频率',
                type: 'bar',
                data: [70, 34, 60, 78, 69],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(
                        0, 0, 1, 0,
                        [
                            {offset: 0, color: '#313695'},
                            {offset: 0.5, color: '#4575b4'},
                            {offset: 1, color: '#74add1'}
                        ]
                    )
                }
            }
        ]
    };

    myChart.setOption(option);

    // 窗口大小变化时重绘图表
    window.addEventListener('resize', function() {
        myChart.resize();
    });

    return myChart;
}

// 初始化环境指标图表
function initEnvironmentChart() {
    const chartDom = document.getElementById('chart-environment');
    const myChart = echarts.init(chartDom);

    const option = {
        backgroundColor: 'rgba(0, 0, 0, 0)',
        title: {
            text: '环境指标监测',
            left: 'center',
            textStyle: {
                color: '#fff',
                fontSize: 14
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#fff'
                }
            }
        },
        legend: {
            data: ['温度(°C)', '湿度(%)', '信号强度(dBm)'],
            textStyle: {
                color: 'rgba(255, 255, 255, 0.7)'
            },
            top: '10%'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '25%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00'],
                axisLine: {
                    lineStyle: {
                        color: 'rgba(255, 255, 255, 0.3)'
                    }
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    color: 'rgba(255, 255, 255, 0.7)'
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '温度/湿度',
                min: 0,
                max: 100,
                axisLine: {
                    lineStyle: {
                        color: 'rgba(255, 255, 255, 0.3)'
                    }
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    color: 'rgba(255, 255, 255, 0.7)'
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    }
                }
            },
            {
                type: 'value',
                name: '信号强度',
                min: -120,
                max: 0,
                axisLine: {
                    lineStyle: {
                        color: 'rgba(255, 255, 255, 0.3)'
                    }
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    color: 'rgba(255, 255, 255, 0.7)'
                },
                splitLine: {
                    show: false
                }
            }
        ],
        series: [
            {
                name: '温度(°C)',
                type: 'line',
                data: [21, 20, 22, 25, 24, 23],
                color: '#FF5722',
                smooth: true
            },
            {
                name: '湿度(%)',
                type: 'line',
                data: [50, 52, 54, 58, 57, 56],
                color: '#2196F3',
                smooth: true
            },
            {
                name: '信号强度(dBm)',
                type: 'line',
                yAxisIndex: 1,
                data: [-85, -87, -90, -92, -91, -90],
                color: '#9C27B0',
                smooth: true
            }
        ]
    };

    myChart.setOption(option);

    // 窗口大小变化时重绘图表
    window.addEventListener('resize', function() {
        myChart.resize();
    });

    return myChart;
}

// 模拟数据更新
function updateCharts() {
    // 更新设备使用频率数据
    const frequencyChart = echarts.getInstanceByDom(document.getElementById('chart-frequency'));
    if (frequencyChart) {
        const newData = [
            Math.floor(Math.random() * 30) + 60,
            Math.floor(Math.random() * 30) + 30,
            Math.floor(Math.random() * 30) + 50,
            Math.floor(Math.random() * 30) + 65,
            Math.floor(Math.random() * 30) + 55
        ];
        frequencyChart.setOption({
            series: [{
                data: newData
            }]
        });
    }

    // 更新环境指标数据
    const environmentChart = echarts.getInstanceByDom(document.getElementById('chart-environment'));
    if (environmentChart) {
        const lastTemp = environmentChart.getOption().series[0].data.slice(-1)[0];
        const lastHumidity = environmentChart.getOption().series[1].data.slice(-1)[0];
        const lastSignal = environmentChart.getOption().series[2].data.slice(-1)[0];

        const newTemp = Math.max(18, Math.min(30, lastTemp + (Math.random() * 2 - 1)));
        const newHumidity = Math.max(40, Math.min(70, lastHumidity + (Math.random() * 4 - 2)));
        const newSignal = Math.max(-100, Math.min(-80, lastSignal + (Math.random() * 4 - 2)));

        const tempData = environmentChart.getOption().series[0].data.slice(1).concat([newTemp.toFixed(1)]);
        const humidityData = environmentChart.getOption().series[1].data.slice(1).concat([newHumidity.toFixed(1)]);
        const signalData = environmentChart.getOption().series[2].data.slice(1).concat([newSignal.toFixed(1)]);

        environmentChart.setOption({
            series: [
                {data: tempData},
                {data: humidityData},
                {data: signalData}
            ]
        });
    }
}